package nsu.grandfinal;

import java.util.ArrayList;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;

public class Tab2 extends ListActivity {
	private static final int	DELETE_ID	= Menu.FIRST;
	private static final int	RESET_ID	= Menu.FIRST + 1;
	private static final int	MODIFY_ID	= Menu.FIRST + 2;
	DatabaseHandle						dbHandle;
	DatabaseHelper						dbHelper;
	int												_id;
	TabHost										mTabHost;
	ArrayList<Integer>				idList		= new ArrayList<Integer>();
	ListAdapter								adapter;
	
	public ListAdapter getAdapter() {
		return adapter;
	}
	
	public void setAdapter(ListAdapter adapter) {
		this.adapter = adapter;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, MODIFY_ID, Menu.NONE, "수정");
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "삭제");
		menu.add(Menu.NONE, RESET_ID, Menu.NONE, "초기화");
		return super.onCreateOptionsMenu(menu);
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		dbHandle = new DatabaseHandle(this).open();
		adapter = new SimpleCursorAdapter(this, R.layout.dblistview, dbHandle.consCursor, new String[] { "name", "address", "range" }, new int[] { R.id.dbname, R.id.dbaddress, R.id.dbrange });
		setListAdapter(adapter);
		registerForContextMenu(getListView());
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		CheckBox cb = (CheckBox) (l.getChildAt(position).findViewById(R.id.checkBox));
		if (cb.isChecked()) {
			cb.setChecked(false);
			idList.remove(id);
		} else {
			cb.setChecked(true);
			idList.add((int) id);
		}
	}
	
	public void onPause() {
		super.onPause();
		dbHandle.close();
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MODIFY_ID:
				AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
				Intent intent = new Intent(this, UserSetting.class);
				intent.putExtra("id", dbHandle.readId(info.id));
				Log.i("id:", dbHandle.readId(info.id) + "");
				intent.putExtra("featureName", dbHandle.readName(info.id));
				intent.putExtra("address", dbHandle.readAddress(info.id));
				intent.putExtra("range", dbHandle.readRange(info.id));
				intent.putExtra("infoID", info.id);
				intent.putExtra("sender", "saveList");
				intent.putExtra("Lat", dbHandle.readLat(info.id));
				intent.putExtra("Lon", dbHandle.readLon(info.id));
				Log.i("Lat:", dbHandle.readLat(info.id) + "");
				Log.i("Lon:", dbHandle.readLon(info.id) + "");
				startActivity(intent);
				break;
		}
		return super.onContextItemSelected(item);
	}
	
	private void delete() {
		if (idList.size() > 0) {
			for (int i = 0; i < idList.size(); i++) {
				AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
				alarm.cancel(PendingIntent.getBroadcast(this, dbHandle.getIntData(idList.get(i), "alarmcode"), getIntent(), 0));
				dbHelper = new DatabaseHelper(this);
				String[] args = { String.valueOf(idList.get(i)) };
				dbHelper.getWritableDatabase().delete("setting", "_id=?", args);
			}
		}
		idList.clear();
		onPause();
		onResume();
	}
	
	private void deleteAll() {
		if (adapter.getCount() > 0) {
			long AID[] = readAllId();
			for (int i = 0; i < adapter.getCount(); i++) {
				AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
				alarm.cancel(PendingIntent.getBroadcast(this, dbHandle.getIntData(AID[i], "alarmcode"), getIntent(), 0));
			}
			dbHandle.dropTable();
			idList.clear();
			onPause();
			onResume();
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case DELETE_ID:
				new AlertDialog.Builder(this).setTitle("삭제하시겠습니까?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						delete();
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {}
				}).show();
				break;
			case RESET_ID: {
				new AlertDialog.Builder(this).setTitle("초기화 하시겠습니까?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						deleteAll();
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {}
				}).show();
				break;
			}
		}
		return true;
	}
	
	public long[] readAllId() {
		long[] AID = new long[adapter.getCount()];
		Log.i("adapterSize():", adapter.getCount() + "");
		for (int i = 0; i < adapter.getCount(); i++) {
			long ad2 = adapter.getItemId(i);
			AID[i] = dbHandle.readId(ad2);
			Log.i("ID" + i, AID[i] + "");
		}
		return AID;
	}
}
